package com.itheima.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.common.BaseContext;
import com.itheima.pojo.Employee;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.time.LocalDateTime;
import java.time.LocalTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private HttpSession session;

    @Override
    public void insertFill(MetaObject metaObject) {
        Employee emp = (Employee) session.getAttribute("emp");
        if (emp != null){
            Long empId = emp.getId();
            this.strictInsertFill(metaObject,"createUser", Long.class,empId);
            this.strictInsertFill(metaObject,"updateUser", Long.class,empId);
        }
        this.strictInsertFill(metaObject,"createUser", Long.class, BaseContext.getCurrentId());
        this.strictInsertFill(metaObject,"updateUser", Long.class,BaseContext.getCurrentId());

        this.strictInsertFill(metaObject,"createTime",LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject,"updateTime",LocalDateTime.class,LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Employee emp = (Employee) session.getAttribute("emp");
        if (emp != null){
            Long empId = emp.getId();
            this.strictUpdateFill(metaObject,"updateUser",Long.class,empId);
        }
        Long userId = (Long) session.getAttribute("userId");
        this.strictUpdateFill(metaObject,"updateUser",Long.class,userId);

        this.strictUpdateFill(metaObject,"updateTime",LocalDateTime.class,LocalDateTime.now());
    }
}
